package com.qf.xiaomi.web.servlet;

import com.qf.xiaomi.pojo.*;
import com.qf.xiaomi.service.impl.orderServiceImpl;
import com.qf.xiaomi.service.orderService;
import com.qf.xiaomi.utils.StringConstans;
import com.qf.xiaomi.web.base.BaseServlet;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * Created by 田贵宾 on 2022/8/20 9:20
 *
 * @author 田贵宾
 * @version 1.0
 * //TODO java练习阶段
 * @since 1.0
 */
@WebServlet("/order")
public class OrderServlet extends BaseServlet {
    orderService service = new orderServiceImpl();

    public String preView(HttpServletRequest req, HttpServletResponse resp){
        TbUser user = (TbUser) req.getSession().getAttribute("user");
        long uid = user.getId();
        List<TbAddress> addressList=service.selectAddressByUid(uid);
        req.setAttribute("addressList",addressList);
        return StringConstans.FORWARD+"/order.jsp";
    }
    public String create(HttpServletRequest req, HttpServletResponse resp){
        //生成订单
        String aidStr = req.getParameter("aid");
        if (aidStr==null){
            return StringConstans.REDIRECT+"/order?method=preView";
        }
        long aid = Long.parseLong(aidStr);
        TbUser user = (TbUser) req.getSession().getAttribute("user");
        if (user==null){
            return StringConstans.REDIRECT+"/login.jsp";
        }
        long uid = user.getId();
        TbCartList cart = (TbCartList) req.getSession().getAttribute("cart");
        if (cart==null||cart.getGoodsList()==null){
            return StringConstans.REDIRECT+"/index.jsp";
        }
        Map order = service.createOrder(aid, uid, cart);
        req.getSession().setAttribute("order",order);
        //下单完成后session域中得购物车 也要清空
        //置空，目的加速垃圾回收
        cart.getGoodsList().clear();
        cart.setNums(null);
        //删除session中购物车得数据
        req.getSession().removeAttribute("cart");

        return StringConstans.REDIRECT+"/orderSuccess.jsp";
    }
    public String show(HttpServletRequest req, HttpServletResponse resp){
        TbUser user = (TbUser) req.getSession().getAttribute("user");
        long uid = user.getId();
        List<TbOrder>orderList = service.selectOrderByUid(uid);
        req.getSession().setAttribute("ordersList",orderList);

        return StringConstans.REDIRECT+"/orderList.jsp";
    }
    public String detail(HttpServletRequest req, HttpServletResponse resp){
        String oid = req.getParameter("oid");

        OrderDetail order = new OrderDetail();
        order=service.findByOid(order,oid);


        req.setAttribute("order",order);
        return StringConstans.FORWARD+"/orderDetail.jsp";
    }
}
